package secondriver.heathfood.exception;

import android.content.Context;
import secondriver.heathfood.util.LogUtil;

/**
 * Author : secondriver
 * Date :  2015/10/27
 */
public class SysUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {


    private static final LogUtil logUtil = LogUtil.getLogger(SysUncaughtExceptionHandler.class.getName());

    private static boolean initState = false;

    private Context context;

    private SysUncaughtExceptionHandler() {
    }

    private static class HandlerHolder {
        static final SysUncaughtExceptionHandler exceptionHandler = new SysUncaughtExceptionHandler();
    }

    public static void initSysUncaughtExceptionHandler(Context context) {
        if (!initState) {
            synchronized (HandlerHolder.exceptionHandler) {
                if (!initState) {
                    HandlerHolder.exceptionHandler.context = context;
                    Thread.setDefaultUncaughtExceptionHandler(HandlerHolder.exceptionHandler);
                    initState = true;
                }
            }
        }
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        String threadName = thread.getName();
        long threadId = thread.getId();
        if ("main".equals(threadName)) {
            logUtil.error("Main thread UncaughtException threadName=%s threadId=%d message=%s.", threadName, threadId, ex.getMessage());

        } else {
            logUtil.error("Sub thread UncaughtException threadName=%s threadId=%d message=%s.", threadName, threadId, ex.getMessage());
        }
        //Do More
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }
}
